package org.geekbang.thinking.in.spring.ioc.dependency.injection;

import org.geekbang.thinking.in.spring.ioc.overview.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import sun.nio.cs.US_ASCII;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.Map;
import java.util.Optional;

/**
 * 注解驱动的依赖注入的处理过程
 *
 * @author <a href="mailto:hushengjin1993@gmail.com">Hu Shengjin</a>
 * @since
 */
public class AnnotationDependencyInjectionResolutionDemo {

    @Autowired              // 依赖查找（处理）
    private User user;      // DependencyDescriptor ->
                            // 必须 （required=true）
                            // 实时注入（eager=true）
                            // 字段名称（"user"）
                            // 是否首要（primary=true）
    @Autowired
    private Map<String, User> users;

    @Autowired
    private Optional<User> userOptional;

    public static void main(String[] args) {
        // 创建 BeanFactory 容器
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        // 注册 Configuration Class (配置类)
        applicationContext.register(AnnotationDependencyInjectionResolutionDemo.class);

        XmlBeanDefinitionReader xmlBeanDefinitionReader = new XmlBeanDefinitionReader(applicationContext);
        String resourcePath = "classpath:/META-INF/dependency-lookup-context.xml";
        xmlBeanDefinitionReader.loadBeanDefinitions(resourcePath);

        // 启动 Spring 应用上下文
        applicationContext.refresh();
        // 依赖查找 AnnotationDependencyFieldInjectionDemo Bean
        AnnotationDependencyInjectionResolutionDemo demo = applicationContext.getBean(AnnotationDependencyInjectionResolutionDemo.class);

        // 期待输出 superUser Bean
        System.out.println("demo.user = " + demo.user);
        // 期待输出 user superUser Bean
        System.out.println("demo.users = " + demo.users);

        System.out.println("demo.userOptional = " + demo.userOptional);
        // 关闭
        applicationContext.close();
    }

}
